package org.itli.jnsocket.Controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.Pojo.Supplier;
import org.itli.jnsocket.Result.Result;
import org.itli.jnsocket.Service.SupplierService;
import org.itli.jnsocket.Util.JWTUtil;
import org.itli.jnsocket.Util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Tag(name = "供应商管理")
@RequestMapping("/Supplier")
@RestController
public class SupplierController {

    SupplierService service;

    JWTUtil jwt = new JWTUtil();

    @Autowired
    public void setService(SupplierService service) {
        this.service = service;
    }

    //查询所有供应商
    @PostMapping("/AllSuppliers")
    @Operation(summary = "查询所有供应商")
    public Result<String> AllSuppliers(@RequestBody PageUtil page) {
        String s = service.AllSuppliers(page);
        return Result.success(s);
    }

    @PostMapping("/AddSupplier")
    @Operation(summary = "添加供应商")
    public Result<String> AddSupplier(@RequestHeader("Authorization") String token, @RequestBody Supplier supplier) {
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        String s = service.AddSupplier(supplier, username);
        return Result.success(s);
    }

    //修改供应商
    @PostMapping("/AlterSupplier")
    @Operation(summary = "修改供应商")
    public Result<String> AlterSupplier(@RequestHeader("Authorization") String token, @RequestBody Supplier supplier) {
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");

        String s = service.AlterSipplier(supplier, username);
        return Result.success(s);
    }

    //删除供应商
    @PostMapping("/DeleteSupplier")
    @Operation(summary = "删除供应商")
    public Result<String> DeleteSupplier(@RequestHeader("Authorization") String token, @RequestBody Supplier supplier) {
        log.info(supplier.toString());
        String s = service.DeleteSupplier(supplier);
        return Result.success(s);
    }

}
